package com.yunxi.core.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.yunxi.core.web.ResponseUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
@Component(value="OSSUtilCore")
public class OSSUtil {
    @Value("${OSS.KEY}")
    public String KEY="LTAITlzonnDhUhVH";
    @Value("${OSS.PASS}")
    public String PASS="zp4lWIad7cGOHKipLKcqG4iTSZGLOP";
    @Value("${OSS.ENDPOINT}")
    public String ENDPOINT="http://oss-cn-shenzhen.aliyuncs.com";
    @Value("${OSS.BUCKET.NAME}")
    public String BucketName="pms-image";
    @Value("${OSS.ENDPOINT.DOMAIN}")
    public String ENDPOINT_DOMAIN="oss-cn-shenzhen.aliyuncs.com";
    @Value("${OSS.READ}")
    public String READ="false";

    public void uploadFile(String object_name,File file) throws FileNotFoundException {
// 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(ENDPOINT, KEY, PASS);
// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        InputStream inputStream = new FileInputStream(file);
        ossClient.putObject(BucketName, object_name, inputStream);
// 关闭OSSClient。
        ossClient.shutdown();
    }

    public void uploadFile(String object_name,MultipartFile file) throws IOException {
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
// 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(ENDPOINT, KEY, PASS);
// 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
        ossClient.putObject(BucketName, object_name, file.getInputStream());
// 关闭OSSClient。
        ossClient.shutdown();
    }

    public String downloadUrl(String sourceUrl) throws IOException {

        if (READ!=null&&READ.equals("true")){
            OSSClient client = new OSSClient(ENDPOINT, KEY, PASS);
            long expireTime = 3600;//64800
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            //key转换
            if(sourceUrl.startsWith("http")){
                sourceUrl = sourceUrl.substring(sourceUrl.indexOf("aliyuncs.com")+13);
            }
            return client.generatePresignedUrl(BucketName,sourceUrl,expiration).toString();
        }
        return sourceUrl;
    }

    /**
     * 根据URL下载文件,转换为二进制数组
     * @param url
     * @return
     */
    public byte[] downloadOSS(String url) {
      OSSClient ossClient = null;
        byte[] bytes = null;
      try {
          ossClient = new OSSClient(ENDPOINT,KEY,PASS);
          long expireTime = 3600;
          long expireEndTime = System.currentTimeMillis()+expireTime*1000;
          Date expiration = new Date(expireEndTime);
          String key = null;
          if(url.startsWith("http")){
              key = url.substring(url.indexOf("aliyuncs.com")+13);
          }
          String realUrl = ossClient.generatePresignedUrl(BucketName, key, expiration).toString();
          realUrl = realUrl.substring(0,realUrl.indexOf("?"));
          realUrl = realUrl.substring(realUrl.lastIndexOf(".com") + 5);

          OSSObject object = ossClient.getObject(new GetObjectRequest(BucketName, realUrl));
          InputStream objectContent = object.getObjectContent();
          try {
              ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
              bytes = new byte[1024 * 4];
              int n = 0;
              while (-1 != (n = objectContent.read(bytes))) {
                  byteArrayOutputStream.write(bytes, 0, n);
              }
              byteArrayOutputStream.close();
              return byteArrayOutputStream.toByteArray();
          }
          catch (IOException e){
              e.printStackTrace();
          }
      }
      catch (Exception e){
          e.printStackTrace();
          throw new RuntimeException(e.getMessage());
      }
      finally {
          if(ossClient != null){
              ossClient.shutdown();
          }
      }
        return bytes;
   }
}
